"""
五子棋界面层
使用Pygame实现图形化界面
"""

import pygame
import sys
from rules import GobangRules
from ai import RandomAI, GreedyAI, MinimaxAI


class GobangGUI:
    """五子棋图形界面类"""
    
    def __init__(self, board_size=15, cell_size=40):
        """
        初始化界面
        :param board_size: 棋盘大小
        :param cell_size: 每个格子的大小（像素）
        """
        self.board_size = board_size
        self.cell_size = cell_size
        self.margin = 50  # 边距
        
        # 计算窗口大小
        self.window_width = self.cell_size * (board_size - 1) + 2 * self.margin
        self.window_height = self.cell_size * (board_size - 1) + 2 * self.margin + 100
        
        # 初始化Pygame
        pygame.init()
        self.screen = pygame.display.set_mode((self.window_width, self.window_height))
        pygame.display.set_caption("五子棋 Gobang")
        self.clock = pygame.time.Clock()
        
        # 颜色定义
        self.COLOR_BG = (220, 179, 92)  # 棋盘背景色
        self.COLOR_LINE = (0, 0, 0)     # 线条颜色
        self.COLOR_BLACK = (0, 0, 0)    # 黑棋
        self.COLOR_WHITE = (255, 255, 255)  # 白棋
        self.COLOR_TEXT = (0, 0, 0)     # 文字颜色
        self.COLOR_BUTTON = (100, 150, 200)  # 按钮颜色
        self.COLOR_BUTTON_HOVER = (120, 170, 220)  # 按钮悬停颜色
        
        # 字体 - 使用系统中文字体
        try:
            # Windows系统尝试使用微软雅黑
            self.font = pygame.font.SysFont('microsoftyahei', 36)
            self.small_font = pygame.font.SysFont('microsoftyahei', 24)
        except:
            try:
                # 备选方案：使用SimHei（黑体）
                self.font = pygame.font.SysFont('simhei', 36)
                self.small_font = pygame.font.SysFont('simhei', 24)
            except:
                # 最后备选：使用任意支持中文的系统字体
                self.font = pygame.font.SysFont('arial', 36)
                self.small_font = pygame.font.SysFont('arial', 24)
        
        # 游戏状态
        self.game_rules = GobangRules(board_size)
        self.ai_player = None  # AI玩家（None表示双人对战）
        self.ai_thinking = False  # AI是否在思考
        
        # 按钮
        self.buttons = self.create_buttons()
        
    def create_buttons(self):
        """创建界面按钮"""
        button_y = self.window_height - 80
        buttons = {
            'restart': pygame.Rect(20, button_y, 100, 40),
            'undo': pygame.Rect(130, button_y, 100, 40),
            'ai_random': pygame.Rect(240, button_y, 100, 40),
            'ai_greedy': pygame.Rect(350, button_y, 100, 40),
            'ai_minimax': pygame.Rect(460, button_y, 100, 40),
        }
        return buttons
    
    def draw_board(self):
        """绘制棋盘"""
        # 填充背景
        self.screen.fill(self.COLOR_BG)
        
        # 绘制网格线
        for i in range(self.board_size):
            # 横线
            start_x = self.margin
            start_y = self.margin + i * self.cell_size
            end_x = self.margin + (self.board_size - 1) * self.cell_size
            end_y = start_y
            pygame.draw.line(self.screen, self.COLOR_LINE, (start_x, start_y), (end_x, end_y), 2)
            
            # 竖线
            start_x = self.margin + i * self.cell_size
            start_y = self.margin
            end_x = start_x
            end_y = self.margin + (self.board_size - 1) * self.cell_size
            pygame.draw.line(self.screen, self.COLOR_LINE, (start_x, start_y), (end_x, end_y), 2)
        
        # 绘制天元和星位
        star_positions = []
        if self.board_size == 15:
            star_positions = [(3, 3), (3, 11), (11, 3), (11, 11), (7, 7)]
        
        for row, col in star_positions:
            x = self.margin + col * self.cell_size
            y = self.margin + row * self.cell_size
            pygame.draw.circle(self.screen, self.COLOR_LINE, (x, y), 5)
    
    def draw_pieces(self):
        """绘制棋子"""
        board = self.game_rules.board
        for row in range(self.board_size):
            for col in range(self.board_size):
                if board[row][col] != 0:
                    x = self.margin + col * self.cell_size
                    y = self.margin + row * self.cell_size
                    color = self.COLOR_BLACK if board[row][col] == 1 else self.COLOR_WHITE
                    pygame.draw.circle(self.screen, color, (x, y), self.cell_size // 2 - 2)
                    # 白棋加黑边
                    if board[row][col] == 2:
                        pygame.draw.circle(self.screen, self.COLOR_LINE, (x, y), self.cell_size // 2 - 2, 2)
        
        # 标记最后一步
        if self.game_rules.move_history:
            last_row, last_col, _ = self.game_rules.move_history[-1]
            x = self.margin + last_col * self.cell_size
            y = self.margin + last_row * self.cell_size
            pygame.draw.circle(self.screen, (255, 0, 0), (x, y), 5)
    
    def draw_status(self):
        """绘制游戏状态信息"""
        # 显示当前玩家
        if self.game_rules.game_over:
            if self.game_rules.winner == 0:
                text = "平局！"
            elif self.game_rules.winner == 1:
                text = "黑棋获胜！"
            else:
                text = "白棋获胜！"
        else:
            current = "黑棋" if self.game_rules.current_player == 1 else "白棋"
            text = f"当前: {current}"
            if self.ai_thinking:
                text += " (AI思考中...)"
        
        text_surface = self.font.render(text, True, self.COLOR_TEXT)
        text_rect = text_surface.get_rect(center=(self.window_width // 2, 20))
        self.screen.blit(text_surface, text_rect)
    
    def draw_buttons(self):
        """绘制按钮"""
        mouse_pos = pygame.mouse.get_pos()
        
        button_labels = {
            'restart': '重新开始',
            'undo': '悔棋',
            'ai_random': '随机AI',
            'ai_greedy': '贪心AI',
            'ai_minimax': 'Minimax',
        }
        
        for name, rect in self.buttons.items():
            # 检查鼠标悬停
            color = self.COLOR_BUTTON_HOVER if rect.collidepoint(mouse_pos) else self.COLOR_BUTTON
            
            # 如果是AI按钮，显示是否选中
            if name.startswith('ai_') and self.ai_player is not None:
                if (name == 'ai_random' and isinstance(self.ai_player, RandomAI)) or \
                   (name == 'ai_greedy' and isinstance(self.ai_player, GreedyAI)) or \
                   (name == 'ai_minimax' and isinstance(self.ai_player, MinimaxAI)):
                    color = (50, 200, 50)  # 绿色表示选中
            
            pygame.draw.rect(self.screen, color, rect, border_radius=5)
            pygame.draw.rect(self.screen, self.COLOR_LINE, rect, 2, border_radius=5)
            
            # 绘制按钮文字
            text_surface = self.small_font.render(button_labels[name], True, self.COLOR_TEXT)
            text_rect = text_surface.get_rect(center=rect.center)
            self.screen.blit(text_surface, text_rect)
    
    def get_board_position(self, mouse_pos):
        """
        将鼠标位置转换为棋盘坐标
        :param mouse_pos: 鼠标位置 (x, y)
        :return: (row, col) 或 None
        """
        x, y = mouse_pos
        
        # 计算最近的交叉点
        col = round((x - self.margin) / self.cell_size)
        row = round((y - self.margin) / self.cell_size)
        
        # 检查是否在有效范围内
        if 0 <= row < self.board_size and 0 <= col < self.board_size:
            # 检查点击是否足够接近交叉点
            actual_x = self.margin + col * self.cell_size
            actual_y = self.margin + row * self.cell_size
            distance = ((x - actual_x) ** 2 + (y - actual_y) ** 2) ** 0.5
            
            if distance < self.cell_size / 2:
                return (row, col)
        
        return None
    
    def handle_click(self, pos):
        """
        处理鼠标点击事件
        :param pos: 鼠标位置
        """
        # 检查按钮点击
        for name, rect in self.buttons.items():
            if rect.collidepoint(pos):
                if name == 'restart':
                    self.restart_game()
                elif name == 'undo':
                    self.undo_move()
                elif name == 'ai_random':
                    self.set_ai(RandomAI(2))
                elif name == 'ai_greedy':
                    self.set_ai(GreedyAI(2))
                elif name == 'ai_minimax':
                    self.set_ai(MinimaxAI(2, depth=3))
                return
        
        # 检查棋盘点击
        if not self.game_rules.game_over and not self.ai_thinking:
            board_pos = self.get_board_position(pos)
            if board_pos:
                row, col = board_pos
                if self.game_rules.make_move(row, col):
                    # 如果是AI对战模式，轮到AI
                    if self.ai_player and not self.game_rules.game_over:
                        self.ai_thinking = True
    
    def restart_game(self):
        """重新开始游戏"""
        self.game_rules.reset()
        self.ai_thinking = False
    
    def undo_move(self):
        """悔棋"""
        if self.ai_player:
            # AI模式下，悔两步（玩家和AI的）
            self.game_rules.undo_move()
            self.game_rules.undo_move()
        else:
            # 双人模式，悔一步
            self.game_rules.undo_move()
        self.ai_thinking = False
    
    def set_ai(self, ai):
        """
        设置AI对手
        :param ai: AI实例，None表示双人对战
        """
        self.ai_player = ai
        self.restart_game()
    
    def ai_move(self):
        """执行AI落子"""
        if self.ai_player and self.ai_thinking and not self.game_rules.game_over:
            if self.game_rules.current_player == self.ai_player.player_id:
                move = self.ai_player.get_move(self.game_rules)
                if move:
                    row, col = move
                    self.game_rules.make_move(row, col)
                self.ai_thinking = False
    
    def run(self):
        """运行游戏主循环"""
        running = True
        
        while running:
            # 处理事件
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:  # 左键点击
                        self.handle_click(event.pos)
            
            # AI思考和落子
            if self.ai_thinking:
                self.ai_move()
            
            # 绘制界面
            self.draw_board()
            self.draw_pieces()
            self.draw_status()
            self.draw_buttons()
            
            pygame.display.flip()
            self.clock.tick(60)  # 60 FPS
        
        pygame.quit()
        sys.exit()


if __name__ == "__main__":
    # 创建并运行游戏
    game = GobangGUI(board_size=15, cell_size=40)
    game.run()
